package com.wpf.filter;

import java.io.IOException;
import java.net.URLDecoder;

import com.wpf.bean.Userbean;
import com.wpf.dao.UserDAO;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

public class CheckLoginFilter implements Filter {
    public CheckLoginFilter() {}
	public void destroy() {}
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse rep = (HttpServletResponse) response;
		HttpSession session = req.getSession();
		UserDAO userdao = new UserDAO();
		Userbean userbean = new Userbean();
		//查看Cookie是否有登录时间
		Cookie[] cookies = req.getCookies();
		String lastLoginTime = null;
		for(int i=0;cookies!=null&&i<cookies.length;i++) {
			if("lastlogintime".equals(cookies[i].getName())) {
				lastLoginTime= URLDecoder.decode(cookies[i].getValue(),"utf-8");
				break;
			}
		}
		String askTip = "";
		if(lastLoginTime==null) {
			askTip="<p><font size='2' color='green'><strong>这是你首次访问本系统</strong></font></p>";
		}else {
			askTip="<p>上次登录时间：<font size='2' color='green'><strong>"+lastLoginTime+"</strong></font></p>";
		}
		session.setAttribute("asktip", askTip);
		//查看Cookie是否有口令
		String loginToken = null;
		for(int i=0;cookies!=null&&i<cookies.length;i++) {
			if("logintoken".equals(cookies[i].getName())) {
				loginToken= URLDecoder.decode(cookies[i].getValue(),"utf-8");
				break;
			}
		}
		//如果存在口令，自动登录
		if(loginToken!=null) {
			String[] FormMessage = loginToken.split("%");
			String ID = FormMessage[0];
			String passWord = FormMessage[1];
			ID = UserDAO.decryptKaiser(ID,1);
			passWord = UserDAO.decryptKaiser(passWord,1);
			int IDNum = Integer.parseInt(ID);
			userbean = userdao.find(IDNum);
			if(userbean!=null&&userbean.getPassword().equals(passWord)){//账户与密码皆正确
				session.setAttribute("username", userbean.getUsername());
				rep.sendRedirect("wpf_index.jsp");
			}else if((userbean==null)||(userbean!=null&&!userbean.getPassword().equals(passWord))) {
				req.setAttribute("logintip", "<font size='1' color='red'>学号不存在或密码过期！</font>");
				//口令失效，删除口令，重新登录
				for(int i=0;cookies!=null&&i<cookies.length;i++) {
					if("logintoken".equals(cookies[i].getName())) {
						cookies[i].setMaxAge(0);
						rep.addCookie(cookies[i]);
						break;
					}
				}
			}
		}
		chain.doFilter(request, response);
	}
	public void init(FilterConfig fConfig) throws ServletException {}
}
